package com.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

public class PropsLoader {

	private List<String> locations;
	public Properties props;

	public PropsLoader(List<String> locations) {
		super();
		this.locations = locations;
		loadProps();
	}

	public void loadProps() {
		props = new Properties();
		if (locations != null && locations.size() > 0) {
			for (String path : locations) {
				try {
					copyProp(props, readProp(path));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void copyProp(Properties rootProp, Properties subProp) {
		Iterator<Object> iter = subProp.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			rootProp.setProperty(key, subProp.getProperty(key));
		}
	}

	private Properties readProp(String classPathLocation) throws Exception {
		Properties prop = new Properties();
		ClassLoader loader = PropsLoader.class.getClassLoader();
		URL url = loader.getResource(classPathLocation);
		InputStream cc = new FileInputStream(new File(url.getFile()));
		prop.load(cc);
		cc.close();
		return prop;
	}
 
	public void updProp(String keyName, String keyValue) {
		try {
			ClassLoader loader = PropsLoader.class.getClassLoader();
			URL url = loader.getResource(locations.get(0));
			OutputStream output = new FileOutputStream(new File(url.getFile()));
			StringBuffer sb = new StringBuffer();
			sb.append("更新");
			sb.append("Key为");
			sb.append(keyName);
			sb.append("的值为");
			sb.append(keyValue);
			this.props.setProperty(keyName, keyValue);
			this.props.store(output, sb.toString());
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<String> getLocations() {
		return locations;
	}

	public void setLocations(List<String> locations) {
		this.locations = locations;
	}

}
